<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
              <!-- <el-option label="区域二" value="beijing"></el-option> -->
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="search">筛选</el-button>
            <el-button type="info" size="small" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubVisible=true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" stripe border>
        <el-table-column label="文章标题" prop="title"></el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间">
          <template slot-scope="scope">
            <span>{{scope.row.pub_date | dtformat}}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot:default="scope">
          <el-button type="danger" size="mini" @click="remove(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="q.pagenum"
            :page-sizes="[2, 3, 5, 10]"
            :page-size="q.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
    </el-card>
        <!-- 发表文章的 Dialog 对话框 -->
        <el-dialog title="发表文章" :visible.sync="pubVisible" fullscreen :before-close="handleClose" @closed="onClosed">
          <el-form :model="pubForm" label-width="80px" :rules="pubFormRules" ref="pubFormRef">
            <el-form-item prop="title" label="文章标题">
              <el-input v-model="pubForm.title" placeholder="请输入文章标题" maxlength="30"></el-input>
            </el-form-item>
            <el-form-item label="文章分类" prop="cate_id">
              <!-- label 是下拉菜单内容  value是反回后端的数据-->
              <el-select v-model="pubForm.cate_id" style="width:100%">
              <el-option label="请选择分类" value=""></el-option>
              <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="文章内容">
              <!-- 使用 v-model 进行双向的数据绑定 -->
              <quill-editor v-model="pubForm.content"></quill-editor>
            </el-form-item>

            <el-form-item label="文章封面">
              <!-- 用来显示封面的图片 -->
              <img :src="url" alt="" class="cover-img" ref="imgRef" v-if="url"/>
              <img src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" v-else/>
              <br />
              <!-- 文件选择框，默认被隐藏 -->
              <input type="file" style="display: none;" accept="image/*" ref="iptFileRef" @change="onFileChange"/>
              <!-- 选择封面的按钮 -->
              <el-button type="text" @click="chooseImg">+ 选择封面</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="pub('已发布')">发布</el-button>
              <el-button type="info" @click="pub('草稿')">存为草稿</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
  </div>
</template>

<script>
import { getCateListAPI } from '@/api/artCate.js'
import { pubArtAPI, getArtListAPI, deleteArtAPI } from '@/api/article.js'
export default {
  name: 'ArtList',
  created () {
    this.initCateList()
    this.initArtList()
  },
  data () {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      pubVisible: false,
      pubForm: {
        title: '', // 文章标题
        cate_id: '',
        content: '',
        cover_img: null,
        state: '' // 文章发表状态
      },
      pubFormRules: {
        title: [
          { required: true, message: '文章标题是必填项', trigger: 'blur' }
        ],
        cate_id: [
          { required: true, message: '文章标题是必填项', trigger: 'change' }
        ]
      },
      cateList: [],
      url: '',
      artList: [], // 文章数据列表
      total: 0 // 数据条数
    }
  },
  methods: {
    // 关闭事件的处理函数
    async handleClose (done) {
      // 询问用户是否确认关闭对话框
      const confirmResult = await this.$confirm('此操作将导致文章信息丢失, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 取消了关闭
      if (confirmResult === 'cancel') return done(false)
      // 确认关闭
      done()
    },
    // 初始化分类列表数据
    async initCateList () {
      const { data: res } = await getCateListAPI()
      // console.log(res)
      if (res.code !== 0) return
      this.cateList = res.data
    },
    chooseImg () {
      this.$refs.iptFileRef.click()
    },
    onFileChange (e) {
      const files = e.target.files
      if (files.length === 0) {
        // 没选择文件
      } else {
        this.pubForm.cover_img = files[0]

        this.url = URL.createObjectURL(files[0])
      }
    },
    pub (state) {
      this.pubForm.state = state
      this.$refs.pubFormRef.validate(async valid => {
        if (!valid || this.pubForm.content === '' || this.pubForm.cover_img === null || this.pubForm.state === '') {
          return this.$message.error('请填写完整表单')
        }
        // 进行格式转换
        const fd = new FormData()
        for (const k in this.pubForm) {
          fd.append(k, this.pubForm[k])
        }
        const { data: res } = await pubArtAPI(fd)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.pubVisible = false
        // 调用请求文章列表数据
        this.initArtList()
      })
    },
    onClosed () {
      // console.log(1)
      this.$refs.pubFormRef.resetFields()
      this.pubForm.content = ''
      this.pubForm.cover_img = null
      this.pubForm.state = ''
      this.url = ''
    },
    async initArtList () {
      const { data: res } = await getArtListAPI(this.q)
      console.log(res)
      if (res.code !== 0) return this.$message.error(res.message)
      this.artList = res.data
      this.total = res.total
    },
    // 页面数据条数发生变化
    handleSizeChange (newsize) {
      this.q.pagesize = newsize
      this.initArtList()
    },
    // 页码值发生变化时
    handleCurrentChange (newpage) {
      this.q.pagenum = newpage
      this.initArtList()
    },
    search () {
      this.q.pagenum = 1
      this.initArtList()
    },
    reset () {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.initArtList()
    },
    async remove (id) {
      // console.log(id)
      const result = await this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result === 'cancel') return
      console.log('调用删除API')
      const { data: res } = await deleteArtAPI(id)
      // console.log(res)
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      // 删除成功时判断 artlist length 是否为1
      if (this.artList.length === 1 && this.q.pagenum > 1) {
        this.q.pagenum--
      }
      this.initArtList()
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
// 设置富文本编辑器的默认最小高度
/deep/ .ql-editor {
  min-height: 300px;
}

// 解决元素对齐问题
/deep/ .ql-snow .ql-picker-label::before {
  position: relative;
  top: -8px;
}

// 解决元素对齐问题
/deep/ .ql-picker-label > svg {
  position: relative;
  top: -6px;
}

// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.el-pagination {
  margin-top: 15px;
}
</style>
